/*
 * Copyright [2013-2021], Alibaba Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.polardbx.transaction.jdbc;

import com.alibaba.polardbx.atom.jdbc.TStatement;
import com.alibaba.polardbx.rpc.pool.XConnection;
import com.alibaba.polardbx.common.jdbc.IStatement;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;

public class DeferredStatement implements TStatement {

    protected final DeferredConnection conn;

    protected final Statement stmt;

    public DeferredStatement(DeferredConnection conn, Statement stmt) {
        this.conn = conn;
        this.stmt = stmt;
    }

    public void addBatch(String sql) throws SQLException {
        stmt.addBatch(sql);
    }

    public void cancel() throws SQLException {
        stmt.cancel();
    }

    public void clearBatch() throws SQLException {
        stmt.clearBatch();
    }

    public void clearWarnings() throws SQLException {
        stmt.clearWarnings();
    }

    public void close() throws SQLException {
        stmt.close();
    }

    public void closeOnCompletion() throws SQLException {
        stmt.closeOnCompletion();
    }

    protected final boolean discardResults(boolean moreResults) throws SQLException {
        if (conn.serverDiscards || conn.isWrapperFor(XConnection.class)) {
            return moreResults;
        }

        moreResults = moreResults || (getUpdateCount() != -1);
        final int discards = conn.discardResults;
        for (int i = 0; i < discards && moreResults; i++) {
            moreResults = getMoreResults() || (getUpdateCount() != -1);
        }
        return moreResults;
    }

    protected final int discardResults(int updateCount) throws SQLException {
        if (conn.serverDiscards || conn.isWrapperFor(XConnection.class)) {
            return updateCount;
        }

        boolean moreResults = (updateCount != -1);
        final int discards = conn.discardResults;
        for (int i = 0; i < discards && moreResults; i++) {
            moreResults = getMoreResults() || ((updateCount = getUpdateCount()) != -1);
        }
        return updateCount;
    }

    protected final long discardResults(long largeUpdateCount) throws SQLException {
        if (conn.serverDiscards || conn.isWrapperFor(XConnection.class)) {
            return largeUpdateCount;
        }

        boolean moreResults = (largeUpdateCount != -1);
        final int discards = conn.discardResults;
        for (int i = 0; i < discards && moreResults; i++) {
            moreResults = getMoreResults() || ((largeUpdateCount = getLargeUpdateCount()) != -1);
        }
        return largeUpdateCount;
    }

    protected final ResultSet discardResults(ResultSet rs) throws SQLException {
        if (conn.serverDiscards || conn.isWrapperFor(XConnection.class)) {
            return rs;
        }

        boolean moreResults = (rs != null) || (getUpdateCount() != -1);
        final int discards = conn.discardResults;
        for (int i = 0; i < discards && moreResults; i++) {
            moreResults = getMoreResults() || (getUpdateCount() != -1);
        }
        return getResultSet();
    }

    public boolean execute(String sql) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.execute(deferredSql));
        } finally {
            conn.afterExecuted();
        }
    }

    public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.execute(deferredSql, autoGeneratedKeys));
        } finally {
            conn.afterExecuted();
        }
    }

    public boolean execute(String sql, int[] columnIndexes) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.execute(deferredSql, columnIndexes));
        } finally {
            conn.afterExecuted();
        }
    }

    public boolean execute(String sql, String[] columnNames) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.execute(deferredSql, columnNames));
        } finally {
            conn.afterExecuted();
        }
    }

    public int[] executeBatch() throws SQLException {
        conn.flushUnsent();

        return stmt.executeBatch();
    }

    public long[] executeLargeBatch() throws SQLException {
        conn.flushUnsent();

        return stmt.executeLargeBatch();
    }

    public long executeLargeUpdate(String sql) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeLargeUpdate(deferredSql));
        } finally {
            conn.afterExecuted();
        }
    }

    public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeLargeUpdate(deferredSql, autoGeneratedKeys));
        } finally {
            conn.afterExecuted();
        }
    }

    public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeLargeUpdate(deferredSql, columnIndexes));
        } finally {
            conn.afterExecuted();
        }
    }

    public long executeLargeUpdate(String sql, String[] columnNames) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeLargeUpdate(deferredSql, columnNames));
        } finally {
            conn.afterExecuted();
        }
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeQuery(deferredSql));
        } finally {
            conn.afterExecuted();
        }
    }

    public int executeUpdate(String sql) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeUpdate(deferredSql));
        } finally {
            conn.afterExecuted();
        }
    }

    public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeUpdate(deferredSql, autoGeneratedKeys));
        } finally {
            conn.afterExecuted();
        }
    }

    public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeUpdate(deferredSql, columnIndexes));
        } finally {
            conn.afterExecuted();
        }
    }

    public int executeUpdate(String sql, String[] columnNames) throws SQLException {
        String deferredSql = conn.beforeExecuting(sql);

        try {
            return discardResults(stmt.executeUpdate(deferredSql, columnNames));
        } finally {
            conn.afterExecuted();
        }
    }

    public Connection getConnection() throws SQLException {
        return stmt.getConnection();
    }

    public int getFetchDirection() throws SQLException {
        return stmt.getFetchDirection();
    }

    public int getFetchSize() throws SQLException {
        return stmt.getFetchSize();
    }

    public ResultSet getGeneratedKeys() throws SQLException {
        return stmt.getGeneratedKeys();
    }

    public long getLargeMaxRows() throws SQLException {
        return stmt.getLargeMaxRows();
    }

    public long getLargeUpdateCount() throws SQLException {
        return stmt.getLargeUpdateCount();
    }

    public int getMaxFieldSize() throws SQLException {
        return stmt.getMaxFieldSize();
    }

    public int getMaxRows() throws SQLException {
        return stmt.getMaxRows();
    }

    public boolean getMoreResults() throws SQLException {
        return stmt.getMoreResults();
    }

    public boolean getMoreResults(int current) throws SQLException {
        return stmt.getMoreResults(current);
    }

    public int getQueryTimeout() throws SQLException {
        return stmt.getQueryTimeout();
    }

    public ResultSet getResultSet() throws SQLException {
        return stmt.getResultSet();
    }

    public int getResultSetConcurrency() throws SQLException {
        return stmt.getResultSetConcurrency();
    }

    public int getResultSetHoldability() throws SQLException {
        return stmt.getResultSetHoldability();
    }

    public int getResultSetType() throws SQLException {
        return stmt.getResultSetType();
    }

    public int getUpdateCount() throws SQLException {
        return stmt.getUpdateCount();
    }

    public SQLWarning getWarnings() throws SQLException {
        return stmt.getWarnings();
    }

    public boolean isCloseOnCompletion() throws SQLException {
        return stmt.isCloseOnCompletion();
    }

    public boolean isClosed() throws SQLException {
        return stmt.isClosed();
    }

    public boolean isPoolable() throws SQLException {
        return stmt.isPoolable();
    }

    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return stmt.isWrapperFor(iface);
    }

    public void setCursorName(String name) throws SQLException {
        stmt.setCursorName(name);
    }

    public void setEscapeProcessing(boolean enable) throws SQLException {
        stmt.setEscapeProcessing(enable);
    }

    public void setFetchDirection(int direction) throws SQLException {
        stmt.setFetchDirection(direction);
    }

    public void setFetchSize(int rows) throws SQLException {
        stmt.setFetchSize(rows);
    }

    public void setLargeMaxRows(long max) throws SQLException {
        stmt.setLargeMaxRows(max);
    }

    public void setMaxFieldSize(int max) throws SQLException {
        stmt.setMaxFieldSize(max);
    }

    public void setMaxRows(int max) throws SQLException {
        stmt.setMaxRows(max);
    }

    public void setPoolable(boolean poolable) throws SQLException {
        stmt.setPoolable(poolable);
    }

    public void setQueryTimeout(int seconds) throws SQLException {
        stmt.setQueryTimeout(seconds);
    }

    public <T> T unwrap(Class<T> iface) throws SQLException {
        return stmt.unwrap(iface);
    }

    @Override
    public void setLocalInfileInputStream(InputStream stream) {
        ((IStatement) stmt).setLocalInfileInputStream(stream);
    }

    @Override
    public InputStream getLocalInfileInputStream() {
        return ((IStatement) stmt).getLocalInfileInputStream();
    }

    @Override
    public String getAppName() {
        return ((IStatement) stmt).getAppName();
    }
}
